/**
 * Created by lesonchan on 2017/9/30.
 */

import Vue from "vue";
import axios from "axios";
import store from "../vuex/store";
import Routers from "vue-router";
import YDUI from "vue-ydui";

Vue.use(YDUI);
Vue.use(Routers)
const host = location.host
const leh_server = host.indexOf('pay.6ewei.com')
const router = new Routers({})
const LoadingConstructor = Vue.extend(require('../components/yd-ls-loading.vue'));
const instance = new LoadingConstructor({
  el: document.createElement('div')
});
LoadingConstructor.prototype.open = (title) => {
  instance.title = title || '加载中';
  document.body.appendChild(instance.$el);
};

LoadingConstructor.prototype.close = function () {
  const el = instance.$el;
  el.parentNode && el.parentNode.removeChild(el);

};

// axios 配置
axios.defaults.timeout = 10000;
if (leh_server !== -1) {
  //测试环境  opid=ow3A2xACd7238ujfLrT3Pq4iZFqs
  axios.defaults.baseURL = 'http://nkwx.6ewei.com';
}else {
  //生产环境  opid=o8HFNwjRIHPvkyVx058W5XAcDc2s
  axios.defaults.baseURL = 'http://nkwx.6ewei.com';
}

//axios.defaults.headers.post['content-Type'] = 'appliction/x-www-form-urlencoded';
// http request 拦截器
axios.interceptors.request.use(
  config => {
    const OPENID = localStorage.openId
   // instance.open('客官请稍等一下哦');
    if (OPENID) {
      let tokens = btoa(OPENID + ':')
      config.headers.Authorization = `Basic ${tokens}`;
    }
    return config;
  },
  err => {
    return Promise.reject(err);
  });

// http response 拦截器
axios.interceptors.response.use(
  response => {
  //  instance.close()
    return response;
  },
  error => {
    instance.close()//??
    if (error.response.status === 401) {
      switch (error.response.request.responseText) {
        case '0':
          break
        case '1':
          break
        case '2':
          break
        case '3':
          window.location = 'index.html#/reg'
          break
        case '4':
          window.location = 'index.html#/reginfo'
          break
        case '5':
          window.location = 'index.html#/regsick'
          break
        default: 
          alert('新用户请先绑定手机！')
          window.location = 'index.html#/reg'
          break
      }
    } else {
      alert('状态代码:' + error.response.status + '  错误信息：' + error.response.statusText)
      return
    }
    // console.log(JSON.stringify(error));//console : Error: Request failed with status code 402
    return Promise.reject(error.response.data)
  });

export default axios;
